package com.guinea.core.spring;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.navigator.menu.MenuRepository;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.guinea.account.service.DictionaryManager;
import com.guinea.account.service.MenuManager;
import com.guinea.account.service.RoleManager;
import com.guinea.svw.service.CommonManager;

/**
 * <p>StartupListener class used to initialize and database settings
 * and populate any application-wide drop-downs.
 * 
 * <p>Keep in mind that this listener is executed outside of OpenSessionInViewFilter,
 * so if you're using Hibernate you'll have to explicitly initialize all loaded data at the 
 * Dao or service level to avoid LazyInitializationException. Hibernate.initialize() works
 * well for doing this.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class StartupListener extends ContextLoaderListener
    implements ServletContextListener {
    
    private static final Log log = LogFactory.getLog(StartupListener.class);

    public void contextInitialized(ServletContextEvent event) {
        if (log.isDebugEnabled()) {
            log.debug("initializing context...");
        }

        // call Spring's context ContextLoaderListener to initialize
        // all the context files specified in web.xml
        super.contextInitialized(event);

        ServletContext context = event.getServletContext();

//        setupContext(context);
    }

    public static void setupContext(ServletContext context) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);
		SessionFactory sessionFactory = (SessionFactory)ctx.getBean("sessionFactory");
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		MenuManager menuManager = (MenuManager) ctx.getBean("menuManager");
		MenuRepository repository = menuManager.getRepository();
		MenuRepository defaultRepository = (MenuRepository) context
				.getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
		repository.setDisplayers(defaultRepository.getDisplayers());
		// get list of possible roles
		context.setAttribute("repository", repository);
		List menus = menuManager.getValid();
		context.setAttribute("menus",menus);

		RoleManager roleManager = (RoleManager) ctx.getBean("roleManager");
		List allRoles = roleManager.getValid();
		context.setAttribute("allRoles", allRoles);
		
		DictionaryManager dictionaryManager = (DictionaryManager) ctx.getBean("dictionaryManager");
		List rootDictionary = dictionaryManager.getRootNodes();
		context.setAttribute("rootDictionary", rootDictionary);
		List leafDictionary = dictionaryManager.getLeafNodes();
		context.setAttribute("leafDictionary", leafDictionary);
		
		tx.commit();
		
		CommonManager commonManager = (CommonManager) ctx.getBean("commonManager");
		List provinces = commonManager.getProvinces();
		context.setAttribute("provinces", provinces);
		List cities = commonManager.getCities();
		context.setAttribute("cities", cities);
		List districts = commonManager.getDistricts();
		context.setAttribute("districts", districts);
		String pcdJson = commonManager.convertPCDToJson(provinces,cities,districts);
		context.setAttribute("pcdJson",pcdJson);
		
		if (log.isDebugEnabled()) {
			log.debug("Initialization complete [OK]");
		}
	}
}
